import { ref } from 'vue'
import Bus from '@/utils/bus'

export function usePolygonRange({ AMap, mapInstance, emits }) {
  const polygonsrange = ref([])
  const drawingPolygon = ref(null)
  const drawingPoints = ref([])
  const isDrawing = ref(false)
  const markers = ref([])
  let tempSelectPolygon: any = {}

  // 清除所有多边形
  function clearPolygonRange() {
    polygonsrange.value.forEach((polygon) => {
      polygon.setMap(null)
    })
    polygonsrange.value = []

    // 清除所有标记点
    clearMarkers()
  }

  // 清除所有标记点
  function clearMarkers() {
    markers.value.forEach((marker) => {
      marker.setMap(null)
    })
    markers.value = []
  }

  // 创建多边形
  function createPolygonRange(area) {
    const polygon = new AMap.value.Polygon({
      path: area.coordinates,
      strokeColor: area.color,
      strokeWeight: 0,
      strokeOpacity: 1,
      fillColor: area.color,
      fillOpacity: 0.15,
      extData: area,
      bubble: true,
    })

    polygon.setMap(mapInstance.value)
    polygonsrange.value.push(polygon)
    return polygon
  }
  function createTempPolygon(coordinates) {
    if (!coordinates || coordinates.length < 3)
      return

    const polygon = new AMap.value.Polygon({
      path: coordinates,
      strokeColor: tempSelectPolygon.color,
      strokeWeight: 0,
      strokeOpacity: 1,
      fillColor: tempSelectPolygon.color,
      fillOpacity: 0.15,
      extData: tempSelectPolygon,
    })

    polygon.setMap(mapInstance.value)
    polygonsrange.value.push(polygon)
    return polygon
  }
  // 开始绘制多边形
  function openDrawPolygonRange({ selectPolygon }) {
    if (isDrawing.value)
      return
    tempSelectPolygon = selectPolygon[0]
    isDrawing.value = true
    drawingPoints.value = []
    clearMarkers()
    // 创建鼠标样式
    mapInstance.value.setDefaultCursor('crosshair')
    // 添加地图点击事件
    mapInstance.value.on('click', onMapClick)
    // 显示提示信息
    Bus.$emit('showPromot', { show: true, submit: true, drawPolygonRange: true })
  }

  // 地图点击事件处理
  function onMapClick(e) {
    if (!isDrawing.value)
      return

    const lnglat = e.lnglat
    const point = [lnglat.lng, lnglat.lat]
    // 添加点到绘制数组
    drawingPoints.value.push(point)
    // 创建标记点
    const marker = new AMap.value.Marker({
      position: lnglat,
      map: mapInstance.value,
      offset: new AMap.value.Pixel(-6, -15),
      icon: new AMap.value.Icon({
        size: new AMap.value.Size(12, 16),
        image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
        imageSize: new AMap.value.Size(12, 16),
      }),
    })

    markers.value.push(marker)

    // 如果有多个点，绘制或更新多边形
    if (drawingPoints.value.length >= 3) {
      if (drawingPolygon.value) {
        // 更新现有多边形
        drawingPolygon.value.setPath(drawingPoints.value)
      }
      else {
        // 创建新多边形
        drawingPolygon.value = createTempPolygon(drawingPoints.value)
      }
    }
    // console.log(drawingPoints.value,'绘制的多边形坐标集');
  }

  // 提交 - 绘制多边形
  function submitPolygonRange() {
    if (!isDrawing.value)
      return
    console.log('结束绘制多边形', isDrawing.value)

    // 如果有有效的多边形，保存它
    if (drawingPolygon.value && drawingPoints.value.length >= 3) {
      // 可以在这里处理最终的多边形，例如发送到服务器
      // const finalPolygon = drawingPolygon.value
      const coordinates = drawingPoints.value
      tempSelectPolygon.coordinates = coordinates
      // 发出事件，让父组件处理
      emits('updatePolygonRange', { updatePolygonObj: tempSelectPolygon })
      // 重置状态
      drawingPolygon.value = null
    }
    else {
      // 如果没有有效的多边形，清除所有内容
      if (drawingPolygon.value) {
        drawingPolygon.value.setMap(null)
        drawingPolygon.value = null
      }
      clearMarkers()
    }

    cancelDrawPolygonRange()
  }

  function cancelDrawPolygonRange() {
    isDrawing.value = false
    mapInstance.value.setDefaultCursor('')
    mapInstance.value.off('click', onMapClick)

    if (drawingPolygon.value) {
      drawingPolygon.value.setMap(null)
      drawingPolygon.value = null
    }
    clearMarkers()
    drawingPoints.value = []
    // 隐藏提示信息
    Bus.$emit('showPromot', { show: false })
    Bus.$emit('showLayerControl', true)
    Bus.$emit('refreshTool', true)
    Bus.$emit('showPromot', { show: false })
  }

  function updatePolygonRange(areas) {
    if (!areas || !areas.length)
      return

    // 检查 AMap 和 Polygon 是否可用
    if (!AMap.value || !AMap.value.Polygon) {
      console.warn('AMap or Polygon is not available yet')
      return
    }

    areas.forEach((area) => {
      createPolygonRange(area)
    })
  }
  return {
    polygonsrange,
    clearPolygonRange,
    createPolygonRange,
    openDrawPolygonRange,
    updatePolygonRange,
    submitPolygonRange,
    cancelDrawPolygonRange,
  }
}
